<template>
  <div class="page-box">
    <universal-table
      :columns="columns"
      :fetch-data="fetchTableData"
      permission-prefix="sys:nfc_deposit"
      :show-selection="true"
      :show-index="true"
      :show-operation="true"
      :operation-width="'280'"
      :bt1-name="''"
      :bt2-name="''"
      :export-file-name="'NFC保证金管理'"
      :init-search-form="{}"
      :custom-export="true"
      :show-keyword-search="true"
      :show-date-range="true"
      @edit="handleEdit"
      @delete="handleDelete"
      @reset="reset"
      @selection-change="handleSelectionChange"
      @custom-export="handleExportCSV"
      ref="table">

      <!-- 搜索区域扩展 -->
      <template #searchExtend>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" placeholder="账户状态" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="balance_range">
          <el-input v-model="searchForm.balance_min" placeholder="最低余额" type="number" style="width: 100px;"></el-input>
          <span style="margin: 0 10px;">-</span>
          <el-input v-model="searchForm.balance_max" placeholder="最高余额" type="number" style="width: 100px;"></el-input>
        </el-form-item>


        <!-- 批量操作按钮区域 -->
        <el-form-item>
          <el-button type="danger" icon="el-icon-lock" @click="handleBatchFreeze" :disabled="!hasSelection">
            批量冻结
          </el-button>
          <el-button type="success" icon="el-icon-unlock" @click="handleBatchUnfreeze" :disabled="!hasSelection">
            批量解冻
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </el-form-item>

      </template>

      <!-- 操作栏扩展 -->
      <template #operationExtend="{ row }">
        <el-tooltip content="查看详情" placement="top">
          <el-button size="mini" type="info" icon="el-icon-view" @click="handleViewDetail(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="支付保证金" placement="top">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="handlePayDeposit(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="退还保证金" placement="top" v-if="row.current_balance > 0">
          <el-button size="mini" type="warning" icon="el-icon-minus" @click="handleRefundDeposit(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="冻结" placement="top" v-if="row.available_balance > 0">
          <el-button size="mini" type="danger" icon="el-icon-lock" @click="handleFreezeDeposit(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="解冻" placement="top" v-if="row.frozen_amount > 0">
          <el-button size="mini" type="success" icon="el-icon-unlock" @click="handleUnfreezeDeposit(row)" circle></el-button>
        </el-tooltip>
      </template>
    </universal-table>

    <!-- 账户详情对话框 -->
    <el-dialog title="保证金账户详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="currentAccount">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>商户名称：</label>
              <span>{{ currentAccount.merchant_name }}</span>
            </div>
            <div class="detail-item">
              <label>商户ID：</label>
              <span>{{ currentAccount.merchant_id }}</span>
            </div>
            <div class="detail-item">
              <label>当前余额：</label>
              <span class="amount">¥{{ currentAccount.current_balance }}</span>
            </div>
            <div class="detail-item">
              <label>冻结金额：</label>
              <span class="amount-danger">¥{{ currentAccount.frozen_amount }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>可用余额：</label>
              <span class="amount-success">¥{{ currentAccount.available_balance }}</span>
            </div>
            <div class="detail-item">
              <label>累计充值：</label>
              <span>¥{{ currentAccount.total_deposit }}</span>
            </div>
            <div class="detail-item">
              <label>累计退款：</label>
              <span>¥{{ currentAccount.total_refund }}</span>
            </div>
            <div class="detail-item">
              <label>账户状态：</label>
              <el-tag :type="currentAccount.status == 1 ? 'success' : 'danger'">
                {{ currentAccount.status == 1 ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </el-col>
        </el-row>

        <!-- 近期交易记录 -->
        <el-divider content-position="left">近期交易记录</el-divider>
        <el-table :data="recentRecords" size="small" max-height="300">
          <el-table-column prop="record_type" label="交易类型" width="100">
            <template slot-scope="scope">
              <el-tag size="mini" :type="getRecordTypeTagType(scope.row.record_type)">
                {{ getRecordTypeText(scope.row.record_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100">
            <template slot-scope="scope">
              <span :class="getAmountClass(scope.row.record_type)">
                {{ formatAmount(scope.row.amount, scope.row.record_type) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="balance_after" label="余额" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.balance_after }}
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" show-overflow-tooltip></el-table-column>
          <el-table-column prop="create_time" label="时间" width="160"></el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 支付保证金对话框 -->
    <el-dialog title="支付保证金" :visible.sync="payDialogVisible" width="500px" @close="resetPayForm">
      <el-form :model="payForm" :rules="payRules" ref="payForm" label-width="100px">
        <el-form-item label="商户名称">
          <el-input v-model="currentMerchant.merchant_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="支付金额" prop="amount">
          <el-input
            v-model="payForm.amount"
            type="number"
            placeholder="请输入支付金额"
            :min="0.01"
            :max="999999.99"
            step="0.01">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="参考号" prop="reference">
          <el-input
            v-model="payForm.reference"
            placeholder="请输入参考号（可选）"
            maxlength="50">
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="payForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注（可选）"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayDeposit" :loading="payLoading">确定支付</el-button>
      </div>
    </el-dialog>

    <!-- 退还保证金对话框 -->
    <el-dialog title="退还保证金" :visible.sync="refundDialogVisible" width="500px" @close="resetRefundForm">
      <el-form :model="refundForm" :rules="refundRules" ref="refundForm" label-width="100px">
        <el-form-item label="商户名称">
          <el-input v-model="currentMerchant.merchant_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="可退金额">
          <el-input :value="`¥${currentMerchant.available_balance}`" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="退还金额" prop="amount">
          <el-input
            v-model="refundForm.amount"
            type="number"
            placeholder="请输入退还金额"
            :min="0.01"
            :max="currentMerchant.available_balance"
            step="0.01">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="参考号" prop="reference">
          <el-input
            v-model="refundForm.reference"
            placeholder="请输入参考号（可选）"
            maxlength="50">
          </el-input>
        </el-form-item>
        <el-form-item label="退还原因" prop="remark">
          <el-input
            v-model="refundForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入退还原因"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="confirmRefundDeposit" :loading="refundLoading">确定退还</el-button>
      </div>
    </el-dialog>

    <!-- 冻结保证金对话框 -->
    <el-dialog title="冻结保证金" :visible.sync="freezeDialogVisible" width="500px" @close="resetFreezeForm">
      <el-form :model="freezeForm" :rules="freezeRules" ref="freezeForm" label-width="100px">
        <el-form-item label="商户名称">
          <el-input v-model="currentMerchant.merchant_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="可冻结金额">
          <el-input :value="`¥${currentMerchant.available_balance}`" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="冻结金额" prop="amount">
          <el-input
            v-model="freezeForm.amount"
            type="number"
            placeholder="请输入冻结金额"
            :min="0.01"
            :max="currentMerchant.available_balance"
            step="0.01">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="冻结原因" prop="reason">
          <el-input
            v-model="freezeForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入冻结原因"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="参考号" prop="reference">
          <el-input
            v-model="freezeForm.reference"
            placeholder="请输入参考号（可选）"
            maxlength="50">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="freezeDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmFreezeDeposit" :loading="freezeLoading">确定冻结</el-button>
      </div>
    </el-dialog>

    <!-- 解冻保证金对话框 -->
    <el-dialog title="解冻保证金" :visible.sync="unfreezeDialogVisible" width="500px" @close="resetUnfreezeForm">
      <el-form :model="unfreezeForm" :rules="unfreezeRules" ref="unfreezeForm" label-width="100px">
        <el-form-item label="商户名称">
          <el-input v-model="currentMerchant.merchant_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="冻结金额">
          <el-input :value="`¥${currentMerchant.frozen_amount}`" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="解冻金额" prop="amount">
          <el-input
            v-model="unfreezeForm.amount"
            type="number"
            placeholder="请输入解冻金额"
            :min="0.01"
            :max="currentMerchant.frozen_amount"
            step="0.01">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="解冻原因" prop="reason">
          <el-input
            v-model="unfreezeForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入解冻原因"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="参考号" prop="reference">
          <el-input
            v-model="unfreezeForm.reference"
            placeholder="请输入参考号（可选）"
            maxlength="50">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="unfreezeDialogVisible = false">取消</el-button>
        <el-button type="success" @click="confirmUnfreezeDeposit" :loading="unfreezeLoading">确定解冻</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import UniversalTable from "@/components/TableComponent.vue";
import { nfcDepositAPI } from '@/api/nfc'
import { handleCSVExportResponse } from '@/utils/exportCSV'

export default {
  name: 'NfcDepositManagement',
  components: { UniversalTable },
  data() {
    return {
      columns: [
        { prop: 'merchant_id', label: '商户ID', width: 100 },
        { prop: 'merchant_name', label: '商户名称', width: 180 },
        { 
          prop: 'current_balance', 
          label: '当前余额', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-text'
            }, `¥${row.current_balance}`)
          }
        },
        { 
          prop: 'frozen_amount', 
          label: '冻结金额', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-danger'
            }, `¥${row.frozen_amount}`)
          }
        },
        { 
          prop: 'available_balance', 
          label: '可用余额', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-success'
            }, `¥${row.available_balance}`)
          }
        },
        { 
          prop: 'total_deposit', 
          label: '累计充值', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-text'
            }, `¥${row.total_deposit}`)
          }
        },
        { 
          prop: 'total_refund', 
          label: '累计退款', 
          width: 120,
          render: (h, { row }) => {
            return h('span', {
              class: 'amount-text'
            }, `¥${row.total_refund}`)
          }
        },
        {
          prop: 'status',
          label: '状态',
          width: 80,
          render: (h, { row }) => {
            return h('el-tag', {
              props: {
                type: row.status == 1 ? 'success' : 'danger',
                size: 'mini'
              }
            }, row.status == 1 ? '启用' : '禁用')
          }
        },
        { prop: 'create_time', label: '创建时间', width: 160 },
        { prop: 'update_time', label: '更新时间', width: 160 }
      ],
      searchForm: {
        status: '',
        balance_min: '',
        balance_max: ''
      },
      selectedRows: [],
      hasSelection: false,

      // 详情对话框
      detailDialogVisible: false,
      currentAccount: null,
      recentRecords: [],

      // 支付对话框
      payDialogVisible: false,
      currentMerchant: {},
      payForm: {
        amount: '',
        reference: '',
        remark: ''
      },
      payRules: {
        amount: [
          { required: true, message: '请输入支付金额', trigger: 'blur' },
          { 
            validator: (_, value, callback) => {
              const numValue = parseFloat(value)
              if (isNaN(numValue) || numValue <= 0) {
                callback(new Error('支付金额必须大于0'))
              } else if (numValue > 999999.99) {
                callback(new Error('支付金额不能超过999999.99元'))
              } else {
                callback()
              }
            }, 
            trigger: 'blur' 
          }
        ]
      },
      payLoading: false,

      // 退还对话框
      refundDialogVisible: false,
      refundForm: {
        amount: '',
        reference: '',
        remark: ''
      },
      refundRules: {
        amount: [
          { required: true, message: '请输入退还金额', trigger: 'blur' },
          { 
            validator: (_, value, callback) => {
              const numValue = parseFloat(value)
              if (isNaN(numValue) || numValue <= 0) {
                callback(new Error('退还金额必须大于0'))
              } else {
                callback()
              }
            }, 
            trigger: 'blur' 
          }
        ],
        remark: [
          { required: true, message: '请输入退还原因', trigger: 'blur' }
        ]
      },
      refundLoading: false,

      // 冻结对话框
      freezeDialogVisible: false,
      freezeForm: {
        amount: '',
        reason: '',
        reference: ''
      },
      freezeRules: {
        amount: [
          { required: true, message: '请输入冻结金额', trigger: 'blur' },
          { 
            validator: (_, value, callback) => {
              const numValue = parseFloat(value)
              if (isNaN(numValue) || numValue <= 0) {
                callback(new Error('冻结金额必须大于0'))
              } else {
                callback()
              }
            }, 
            trigger: 'blur' 
          }
        ],
        reason: [
          { required: true, message: '请输入冻结原因', trigger: 'blur' }
        ]
      },
      freezeLoading: false,

      // 解冻对话框
      unfreezeDialogVisible: false,
      unfreezeForm: {
        amount: '',
        reason: '',
        reference: ''
      },
      unfreezeRules: {
        amount: [
          { required: true, message: '请输入解冻金额', trigger: 'blur' },
          { 
            validator: (_, value, callback) => {
              const numValue = parseFloat(value)
              if (isNaN(numValue) || numValue <= 0) {
                callback(new Error('解冻金额必须大于0'))
              } else {
                callback()
              }
            }, 
            trigger: 'blur' 
          }
        ],
        reason: [
          { required: true, message: '请输入解冻原因', trigger: 'blur' }
        ]
      },
      unfreezeLoading: false
    }
  },
  methods: {
    downloadBlob(res, defaultName) {
      try {
        const blob = new Blob([res.data], { type: res.headers['content-type'] || 'application/octet-stream' })
        const cd = res.headers['content-disposition'] || ''
        let filename = defaultName
        const match = cd.match(/filename\*=UTF-8''([^;\n]+)/) || cd.match(/filename="?([^";]+)"?/)
        if (match && match[1]) {
          filename = decodeURIComponent(match[1])
        }
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = filename
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
      } catch (e) {
        console.error('下载文件失败', e)
      }
    },
    // 获取表格数据
    async fetchTableData(params) {
      const searchParams = {
        ...params,
        ...this.searchForm
      }
      
      const response = await nfcDepositAPI.getList(searchParams)
      return {
        list: response.data,
        total: response.count
      }
    },


    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.hasSelection = selection.length > 0
    },

    // 查看详情
    async handleViewDetail(row) {
      try {
        const response = await nfcDepositAPI.getInfo(row.merchant_id)
        this.currentAccount = response.data.account
        this.recentRecords = response.data.recent_history || []
        this.detailDialogVisible = true
      } catch (error) {
        this.$message.error('获取账户详情失败：' + error.message)
      }
    },

    // 支付保证金
    handlePayDeposit(row) {
      this.currentMerchant = { ...row }
      this.payDialogVisible = true
    },

    // 确认支付保证金
    async confirmPayDeposit() {
      this.$refs.payForm.validate(async (valid) => {
        if (valid) {
          this.payLoading = true
          try {
            const params = {
              merchant_id: this.currentMerchant.merchant_id,
              ...this.payForm
            }
            await nfcDepositAPI.pay(params)
            this.$message.success('保证金支付成功')
            this.payDialogVisible = false
            this.handleRefresh()
          } catch (error) {
            this.$message.error('支付失败：' + error.message)
          } finally {
            this.payLoading = false
          }
        }
      })
    },

    // 退还保证金
    handleRefundDeposit(row) {
      this.currentMerchant = { ...row }
      this.refundDialogVisible = true
    },

    // 确认退还保证金
    async confirmRefundDeposit() {
      this.$refs.refundForm.validate(async (valid) => {
        if (valid) {
          this.refundLoading = true
          try {
            const params = {
              merchant_id: this.currentMerchant.merchant_id,
              ...this.refundForm
            }
            await nfcDepositAPI.refund(params)
            this.$message.success('保证金退还成功')
            this.refundDialogVisible = false
            this.handleRefresh()
          } catch (error) {
            this.$message.error('退还失败：' + error.message)
          } finally {
            this.refundLoading = false
          }
        }
      })
    },

    // 冻结保证金
    handleFreezeDeposit(row) {
      this.currentMerchant = { ...row }
      this.freezeDialogVisible = true
    },

    // 确认冻结保证金
    async confirmFreezeDeposit() {
      this.$refs.freezeForm.validate(async (valid) => {
        if (valid) {
          this.freezeLoading = true
          try {
            const params = {
              merchant_id: this.currentMerchant.merchant_id,
              ...this.freezeForm
            }
            await nfcDepositAPI.freeze(params)
            this.$message.success('保证金冻结成功')
            this.freezeDialogVisible = false
            this.handleRefresh()
          } catch (error) {
            this.$message.error('冻结失败：' + error.message)
          } finally {
            this.freezeLoading = false
          }
        }
      })
    },

    // 解冻保证金
    handleUnfreezeDeposit(row) {
      this.currentMerchant = { ...row }
      this.unfreezeDialogVisible = true
    },

    // 确认解冻保证金
    async confirmUnfreezeDeposit() {
      this.$refs.unfreezeForm.validate(async (valid) => {
        if (valid) {
          this.unfreezeLoading = true
          try {
            const params = {
              merchant_id: this.currentMerchant.merchant_id,
              ...this.unfreezeForm
            }
            await nfcDepositAPI.unfreeze(params)
            this.$message.success('保证金解冻成功')
            this.unfreezeDialogVisible = false
            this.handleRefresh()
          } catch (error) {
            this.$message.error('解冻失败：' + error.message)
          } finally {
            this.unfreezeLoading = false
          }
        }
      })
    },

    // 批量冻结
    handleBatchFreeze() {
      if (!this.hasSelection) {
        this.$message.warning('请先选择要冻结的账户')
        return
      }
      
      this.$prompt('请输入冻结原因', '批量冻结保证金', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '冻结原因不能为空'
          }
          return true
        }
      }).then(({ value }) => {
        this.performBatchOperation('freeze', { reason: value })
      }).catch(() => {
        // 用户取消操作
      })
    },

    // 批量解冻
    handleBatchUnfreeze() {
      if (!this.hasSelection) {
        this.$message.warning('请先选择要解冻的账户')
        return
      }
      
      this.$prompt('请输入解冻原因', '批量解冻保证金', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '解冻原因不能为空'
          }
          return true
        }
      }).then(({ value }) => {
        this.performBatchOperation('unfreeze', { reason: value })
      }).catch(() => {
        // 用户取消操作
      })
    },

    // 执行批量操作
    async performBatchOperation(type, params) {
      try {
        const operations = this.selectedRows.map(row => ({
          type: type,
          merchant_id: row.merchant_id,
          amount: type === 'freeze' ? row.available_balance : row.frozen_amount,
          ...params
        }))

        await nfcDepositAPI.batchProcess({
          operations: operations,
          atomic_mode: false
        })

        this.$message.success(`批量${type === 'freeze' ? '冻结' : '解冻'}操作完成`)
        this.handleRefresh()
      } catch (error) {
        this.$message.error(`批量操作失败：${error.message}`)
      }
    },

    // 导出CSV数据（与授权页一致的交互与处理）
    async handleExportCSV() {
      try {
        // 构建导出参数，默认导出筛选结果
        const exportParams = {
          ...this.searchForm,
          mode: 'filter'
        }

        // 如果有选中数据，提示用户选择导出方式
        if (this.selectedRows.length > 0) {
          const action = await this.$confirm(
            `检测到已选中 ${this.selectedRows.length} 条记录，请选择导出方式：`,
            '选择导出方式',
            {
              confirmButtonText: '导出选中记录',
              cancelButtonText: '导出筛选结果',
              distinguishCancelAndClose: true,
              type: 'info'
            }
          ).then(() => 'selected').catch(action => {
            if (action === 'cancel') {
              return 'filter'
            }
            return null // 关闭对话框
          })

          if (!action) {
            return // 用户取消导出
          }

          if (action === 'selected') {
            exportParams.mode = 'selected'
            exportParams.ids = this.selectedRows.map(row => row.merchant_id)
          }
        }

        // 调用导出API
        this.$message.info('正在生成CSV文件，请稍候...')
        const response = await nfcDepositAPI.export(exportParams)

        // 处理下载，统一使用工具方法
        const result = handleCSVExportResponse(response, 'NFC保证金管理.csv')
        if (result.success) {
          this.$message.success(`导出成功：${result.filename}`)
        } else {
          throw new Error(result.error)
        }
      } catch (error) {
        console.error('CSV导出失败:', error)
        // 详细错误处理
        let errorMessage = '导出失败'
        if (error.response) {
          if (error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message
          } else {
            errorMessage = `服务器错误: ${error.response.status}`
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        this.$message.error(errorMessage)
      }
    },

    // 工具方法
    getRecordTypeText(type) {
      const typeMap = {
        1: '充值', // RECORD_TYPE_DEPOSIT
        2: '退款', // RECORD_TYPE_REFUND
        3: '冻结', // RECORD_TYPE_FREEZE
        4: '解冻', // RECORD_TYPE_UNFREEZE
        5: '扣款'  // RECORD_TYPE_DEBIT
      }
      return typeMap[type] || `未知类型(${type})`
    },

    getRecordTypeTagType(type) {
      const typeMap = {
        1: 'success', // RECORD_TYPE_DEPOSIT - 充值（绿色）
        2: 'warning', // RECORD_TYPE_REFUND - 退款（橙色）
        3: 'danger',  // RECORD_TYPE_FREEZE - 冻结（红色）
        4: 'info',    // RECORD_TYPE_UNFREEZE - 解冻（蓝色）
        5: 'warning'  // RECORD_TYPE_DEBIT - 扣款（橙色）
      }
      return typeMap[type] || 'info'
    },

    getAmountClass(type) {
      if (type === 1 || type === 4) { // 充值、解冻 - 增加可用余额
        return 'amount-success'
      } else if (type === 2 || type === 3 || type === 5) { // 退款、冻结、扣款 - 减少可用余额
        return 'amount-danger'
      }
      return 'amount-text'
    },

    formatAmount(amount, type) {
      // 1=充值, 4=解冻 显示为正数（+）
      // 2=退款, 3=冻结, 5=扣款 显示为负数（-）
      const prefix = (type === 1 || type === 4) ? '+' : '-'
      return `${prefix}¥${amount}`
    },

    // 重置表单
    resetPayForm() {
      this.$refs.payForm && this.$refs.payForm.resetFields()
      this.payForm = { amount: '', reference: '', remark: '' }
    },

    resetRefundForm() {
      this.$refs.refundForm && this.$refs.refundForm.resetFields()
      this.refundForm = { amount: '', reference: '', remark: '' }
    },

    resetFreezeForm() {
      this.$refs.freezeForm && this.$refs.freezeForm.resetFields()
      this.freezeForm = { amount: '', reason: '', reference: '' }
    },

    resetUnfreezeForm() {
      this.$refs.unfreezeForm && this.$refs.unfreezeForm.resetFields()
      this.unfreezeForm = { amount: '', reason: '', reference: '' }
    },

    // 通用方法
    handleEdit() {
      // 编辑功能暂时不需要
    },

    handleDelete() {
      // 删除功能暂时不需要
    },

    reset() {
      this.searchForm = {
        status: '',
        balance_min: '',
        balance_max: ''
      }
    },

    handleRefresh() {
      this.$refs.table.refresh()
    }
  }
}
</script>

<style scoped>
.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  min-width: 100px;
  color: #606266;
}

.amount-text {
  color: #303133;
  font-weight: 600;
}

.amount-success {
  color: #67C23A;
  font-weight: 600;
}

.amount-danger {
  color: #F56C6C;
  font-weight: 600;
}

.page-box {
  padding: 20px;
}
</style>
